package com.automation.utils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.time.Duration;

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.options.UiAutomator2Options;
import org.openqa.selenium.Dimension;

public class AppiumUSBDeviceReader extends JFrame {

    private JTextArea outputArea;
    private JButton connectButton;
    private JButton readInfoButton;
    private AndroidDriver driver;
    private String deviceId;

    public AppiumUSBDeviceReader() {
        super("Appium USB设备访问");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 顶部面板
        JPanel topPanel = new JPanel();
        topPanel.setBackground(new Color(240, 240, 245));
        topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        connectButton = new JButton("连接设备");
        connectButton.setBackground(new Color(65, 105, 225));
        connectButton.setForeground(Color.WHITE);
        connectButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        connectButton.addActionListener(new ConnectButtonListener());

        readInfoButton = new JButton("读取设备信息");
        readInfoButton.setBackground(new Color(50, 205, 50));
        readInfoButton.setForeground(Color.WHITE);
        readInfoButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        readInfoButton.setEnabled(false);
        readInfoButton.addActionListener(new ReadInfoButtonListener());

        topPanel.add(connectButton);
        topPanel.add(readInfoButton);
        add(topPanel, BorderLayout.NORTH);

        // 输出区域
        outputArea = new JTextArea();
        outputArea.setEditable(false);
        outputArea.setFont(new Font("Consolas", Font.PLAIN, 14));
        outputArea.setBackground(new Color(30, 30, 35));
        outputArea.setForeground(new Color(220, 220, 220));

        JScrollPane scrollPane = new JScrollPane(outputArea);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        add(scrollPane, BorderLayout.CENTER);

        // 状态栏
        JLabel statusLabel = new JLabel("准备连接设备...");
        statusLabel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
        statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        statusLabel.setForeground(Color.DARK_GRAY);
        add(statusLabel, BorderLayout.SOUTH);

        setLocationRelativeTo(null);
    }

    private void appendOutput(String text) {
        outputArea.append(text + "\n");
        outputArea.setCaretPosition(outputArea.getDocument().getLength());
    }

    private void clearOutput() {
        outputArea.setText("");
    }

    private class ConnectButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            new Thread(() -> {
                connectButton.setEnabled(false);
                clearOutput();

                try {
                    appendOutput("步骤 1: 检查ADB连接...");
                    // 获取设备ID
                    Process process = Runtime.getRuntime().exec("adb devices");
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

                    String line;
                    boolean deviceFound = false;
                    while ((line = reader.readLine()) != null) {
                        appendOutput(line);
                        if (line.endsWith("device")) {
                            deviceId = line.split("\\s+")[0];
                            deviceFound = true;
                        }
                    }

                    if (!deviceFound || deviceId == null) {
                        appendOutput("\n错误: 未找到连接的设备。请确保:");
                        appendOutput("1. USB调试已启用");
                        appendOutput("2. 设备已通过USB连接");
                        appendOutput("3. 已安装ADB驱动");
                        return;
                    }

                    appendOutput("\n找到设备: " + deviceId);

                    appendOutput("\n步骤 2: 启动Appium服务器连接...");
                    appendOutput("使用默认地址: http://127.0.0.1:4723");

                    // 配置设备参数
//                    UiAutomator2Options options = new UiAutomator2Options()
//                            .setUdid(deviceId)
//                            .setPlatformName("Android")
//                            .setAutomationName("uiautomator2")
//                            .setAppPackage("com.android.settings")
//                            .setAppActivity(".Settings")
//                            .setNoReset(true);
                    UiAutomator2Options options = new UiAutomator2Options();

                    // 2. 设置基础能力
                    options.setPlatformName("Android");
                    options.setPlatformVersion("7.1.2");
                    options.setUdid(deviceId); // 关键：只设置udid
                    options.setAutomationName("UiAutomator2");

                    // 3. 应用配置
//            options.setAppPackage("com.netease.cloudmusic");
                    options.setAppActivity(".activity.MainActivity");

                    // 4. 键盘和权限设置
//            options.setUnicodeKeyboard(true);
//            options.setResetKeyboard(true);
                    options.setAutoGrantPermissions(true);

                    // 5. 会话设置
                    options.setNoReset(true);
                    options.setNewCommandTimeout(Duration.ofSeconds(3600));
                    options.setEnsureWebviewsHavePages(true);
                    options.setNativeWebScreenshot(true);
//            options.setConnectHardwareKeyboard(true);

                    // 6. 雷电模拟器专用优化
                    options.setCapability("systemPort", 8200);
                    options.setCapability("unicodeKeyboard", true);  // 启用Unicode输入
                    options.setCapability("skipDeviceInitialization", true);
                    options.setCapability("skipServerInstallation", true);
                    options.setCapability("disableAndroidWatchers", true);

                    appendOutput("\n设备配置:");
                    appendOutput("  UDID: " + deviceId);
                    appendOutput("  平台: Android");
                    appendOutput("  自动化引擎: UiAutomator2");
                    appendOutput("  目标应用: 系统设置");

                    appendOutput("\n步骤 3: 初始化AndroidDriver...");
                    driver = new AndroidDriver(new URL("http://127.0.0.1:4723"), options);

                    appendOutput("\n连接成功！");
                    appendOutput("设备会话ID: " + driver.getSessionId());

                    readInfoButton.setEnabled(true);
                } catch (Exception ex) {
                    appendOutput("\n连接失败: " + ex.getMessage());
                    appendOutput("请确保:");
                    appendOutput("1. Appium服务器正在运行 (appium)");
                    appendOutput("2. 设备USB调试已启用");
                    appendOutput("3. 设备已授权USB调试");
                    ex.printStackTrace();
                } finally {
                    connectButton.setEnabled(true);
                }
            }).start();
        }
    }

    private class ReadInfoButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (driver == null) {
                appendOutput("\n错误: 尚未连接到设备");
                return;
            }

            new Thread(() -> {
                readInfoButton.setEnabled(false);

                try {
                    appendOutput("\n正在读取设备信息...");

                    // 获取设备基本信息
                    String deviceName = driver.getCapabilities().getCapability("deviceName").toString();
                    String platformVersion = driver.getCapabilities().getCapability("platformVersion").toString();
                    String manufacturer = driver.getCapabilities().getCapability("deviceManufacturer").toString();
                    String model = driver.getCapabilities().getCapability("deviceModel").toString();

                    appendOutput("\n基本设备信息:");
                    appendOutput("  设备名称: " + deviceName);
                    appendOutput("  安卓版本: " + platformVersion);
                    appendOutput("  制造商: " + manufacturer);
                    appendOutput("  型号: " + model);

                    // 获取设备状态
                    boolean isDeviceLocked = driver.isDeviceLocked();
                    String batteryState = driver.getBatteryInfo().getState().name();
                    double batteryLevel = driver.getBatteryInfo().getLevel();
                    appendOutput("\n设备状态:");
                    appendOutput("  设备锁定: " + isDeviceLocked);
                    appendOutput("  电池状态: " + batteryState);
                    appendOutput("  电量: " + batteryLevel + "%");

                    // 获取当前上下文和应用信息
                    String currentContext = driver.getContext();
                    String currentPackage = driver.getCurrentPackage();
                    String currentActivity = driver.currentActivity();

                    appendOutput("\n当前应用:");
                    appendOutput("  上下文: " + currentContext);
                    appendOutput("  包名: " + currentPackage);
                    appendOutput("  活动: " + currentActivity);

                    // 获取屏幕信息
                    Dimension screenSize = driver.manage().window().getSize();
                    appendOutput("\n屏幕信息:");
                    appendOutput("  分辨率: " + screenSize.getWidth() + "x" + screenSize.getHeight());

                    // 获取设备时间
                    String deviceTime = driver.getDeviceTime();
                    appendOutput("  设备时间: " + deviceTime);

                    // 获取系统属性
                    String language = driver.executeScript("mobile: shell",
                            Utils.arg("command", "getprop persist.sys.locale")).toString();
                    String density = driver.executeScript("mobile: shell",
                            Utils.arg("command", "wm density")).toString();

                    appendOutput("\n系统属性:");
                    appendOutput("  语言: " + language);
                    appendOutput("  屏幕密度: " + density);

                    appendOutput("\n操作完成！");
                } catch (Exception ex) {
                    appendOutput("\n读取设备信息时出错: " + ex.getMessage());
                } finally {
                    readInfoButton.setEnabled(true);
                }
            }).start();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                // 设置系统UI风格
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }

            AppiumUSBDeviceReader app = new AppiumUSBDeviceReader();
            app.setVisible(true);
        });
    }
}

class Utils {
    public static String arg(String key, String value) {
        return String.format("{\"%s\": \"%s\"}", key, value);
    }
}